package com.excel;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Description:
 *
 * @Create 2023/7/19 20:21
 * @Version 1.0
 */
public class TestExcel {
    public static void main(String[] args) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("sheet名称");

        wb.setSheetOrder("sheet名称",0);

        HSSFCellStyle lockstyle = wb.createCellStyle();
        lockstyle.setLocked(true);//设置锁定
        lockstyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        lockstyle.setFillForegroundColor(IndexedColors.RED.getIndex());
        //设置上锁的单元格背景色
        HSSFCellStyle unlockStyle = wb.createCellStyle();
        unlockStyle.setLocked(false);
        //设置未锁定
        for (int i = 0; i < 10; i++) {
            HSSFRow row = sheet.createRow(i);
            for (int j = 0; j < 10; j++) {
                HSSFCell cell = row.createCell(j);
                cell.setCellStyle(unlockStyle);
                //默认是锁定状态&＃xff1b;将所有单元格设置为&＃xff1a;未锁定&＃xff1b;然后再对需要上锁的单元格单独锁定
                if (j == 1) {
                    //这里可以根据需要进行判断;我这就将第2列上锁了
                    cell.setCellStyle(lockstyle);
                    //将需要上锁的单元格进行锁定
                    cell.setCellValue("上锁了");
                } else {
                    cell.setCellValue("没上锁了");
                }
            }
        }
        //sheet添加保护&＃xff0c;这个一定要否则光锁定还是可以编辑的
        sheet.protectSheet("");
        FileOutputStream os = new FileOutputStream("workbook.xls");
        wb.write(os);
        os.close();
    }
}
